package org.dkakunsi.aplikasitoko.data.adapter;

import java.util.List;

import org.dkakunsi.aplikasitoko.data.access.TransaksiBarangDataAccess;
import org.dkakunsi.aplikasitoko.data.entity.TransaksiBarang;
import org.dkakunsi.aplikasitoko.data.util.ApplicationDataException;
import org.dkakunsi.aplikasitoko.data.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;

public class TransaksiBarangDataAdapter implements TransaksiBarangDataAccess {
	
	private Session session;
	private Transaction tx;
	
	public TransaksiBarangDataAdapter() {
		this.session = HibernateUtil.openSession();
		this.tx = session.beginTransaction();
	}
	
	public TransaksiBarangDataAdapter(Session session) {
		this.session = session;
		this.tx = session.beginTransaction();
	}

	@Override
	public void save(Object object) throws ApplicationDataException {
		TransaksiBarang tb = null;
		
		try {
			tb = (TransaksiBarang) object;
			
			session.save(tb);
			tx.commit();
		} catch(ConstraintViolationException x) {
			throw new ApplicationDataException("Duplikasi data untuk KODE : " +tb.getKode());
		}

	}

	@Override
	public void update(Object object) throws Exception {
		TransaksiBarang tb = (TransaksiBarang) object;
		
		session.merge(tb);
		tx.commit();
	}

	@Override
	public void delete(Object object) throws Exception {
		TransaksiBarang tb = (TransaksiBarang) object;
		
		session.delete(tb);
		tx.commit();
	}

	@Override
	public Object getByID(String id) throws ApplicationDataException {
		Long idLong = Long.parseLong(id);
		TransaksiBarang tb = (TransaksiBarang) session.get(TransaksiBarang.class, idLong);
		tx.commit();
		
		if(tb != null){
			return tb;
		} else {
			throw new ApplicationDataException("File Not Found");
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<org.dkakunsi.aplikasitoko.data.entity.TransaksiBarang> getAll() throws Exception {
		List<org.dkakunsi.aplikasitoko.data.entity.TransaksiBarang> all = null;
		
		Session session = HibernateUtil.openSession();
		all = session.createQuery("from TransaksiBarang tb order by tb.kode").list();

		return all;
	}
	
	@Override
	public Session getSession() {
		return this.session;
	}

	@Override
	public Object getBy(String nama) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
}
